package com.cskaoyan.order.mq.producer;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.nio.charset.Charset;

/**
 * @author gatsby
 * @since 2022/10/29 16:12
 */
@Component
@Slf4j
public class DelayOrderCancelProducer {

    private DefaultMQProducer producer;

    @PostConstruct
    public void init() {
        //创建发送延迟消息的producer
        producer = new DefaultMQProducer("delay_order_cancel_producer");
        //指定nameserver地址
        producer.setNamesrvAddr("127.0.0.1:9876");
        //启动producer
        try {
            producer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }

    }

    /**
     * 发送延迟消息的业务逻辑
     *
     * @param orderId
     * @return void
     * @author gatsby
     * @since 2022/10/29 16:19
     */
    public boolean sendDelayOrderMessage(String orderId) {
        log.info("准备发送延迟消息");
        //准备发送的消息
        Message message = new Message();
        message.setTopic("order_delay_cancel");
        message.setBody(orderId.getBytes(Charset.forName("utf-8")));
        message.setDelayTimeLevel(3);
        //发送消息
        SendResult send = null;
        try {
            log.info("pre send msg {}", orderId);
            send = producer.send(message);
        } catch (MQClientException e) {
            e.printStackTrace();
        } catch (RemotingException e) {
            e.printStackTrace();
        } catch (MQBrokerException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("post send msg {} {}", orderId, send.getSendStatus());
        if (send != null && SendStatus.SEND_OK.equals(send.getSendStatus())) {
            log.info("send msg success {}", orderId);
            return true;
        }
        log.info("send msg fail {}",orderId);
        //消息发送失败
        return false;
    }
}
